package sugarbind_input

//http://grails.org/doc/latest/guide/GORM.html#ormdsl

class Agent {

	String agent_Name
	String agent_Notes
	Integer taxonomy_Id
	String agent_Ref
	Integer article_Import_Ref
	
	Agent agent_Parent

    static constraints = {
		agent_Name(blank:false)
		agent_Notes(nullable:true)
		taxonomy_Id(nullable:true)
		agent_Ref(nullable:true)
		agent_Parent(nullable:true)
		article_Import_Ref(nullable:true)		
		agent_Type(nullable:true)
		
		agent_Name(unique:['agent_Type', 'agent_Parent', 'article_Import_Ref']) //if agent name is unknown, check also the reference article 
	}
	
	static hasOne = [agent_Type:Agent_Type]
	static hasMany = [agent_Synonyms:Agent_Synonym, lectin_Support:Lectin_Support, agent_Properties:Agent_Property, disease_Area_Agents:Disease_Area_Agent]
	
	static mapping = {
		
//		table 'agent'
//		id column: 'agent_id'
		id generator: 'sequence', params: [sequence: 'agent_id_seq']
		
		agent_Properties joinTable: [name: "agent_agent_property", key: 'agent_id']
	}
	
	public String toString(){
//		def s =""
//		if(this.agent_Parent!=null)
//		{
//			s = this.agent_Parent.agent_Name
//		}
//		agent_Name 
		getFullName()  + " (" + id + ") " //+ getLineage()
//		return s
	}
	
	public String getFullName(){
		List<Agent> lineage = new ArrayList<Agent>();
		String fullName = "";
		Agent current=this
		Agent parent=null
		
		lineage.add(current)		
		
		while(current.agent_Parent!=null)
		{
			current=current.agent_Parent
			lineage.add(current)
		}		
		
		Collections.reverse(lineage);
		
		for(Agent agent : lineage)
		{
			fullName += " " + agent.agent_Name
		}
		return fullName
	}
	
	
	//FIXME
	public String getLineage(){
		String lineage
		if(this.agent_Parent!=null)
			{
				lineage = this.agent_Parent.agent_Name + " " + this.agent_Name 
			}
		else
			{
				lineage = this.agent_Name
			} 
		
		return lineage()
	}
	
	public static listAgents()
	{
		def l = Agent.findAllByAgent_TypeIsNotNull()
		println(l.get(0).getClass())
		return l
//		Agent.findAll()
	}
//		println(Agent.findAllByAgent_TypeIsNotNull().getClass())
//		println(Agent.findAllByAgent_TypeIsNotNull())
//		ArrayList<Agent> agents = 
//		findAllByAgent_TypeIsNotNull()
//		def alist = Agent.list().sort{ it.toString(); }
//		println(alist.getClass() + " " + alist)
//		return alist
//		return agents
//	}
}
